package sdk.webview.fmc.com.fmcsdk.util;

import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import java.util.Map;

public class SharedPrefUtils {

    private static final String PREF_NAME = "app_prefs";
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private static SharedPrefUtils instance;
    private Gson gson;

    private SharedPrefUtils(Context context) {
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        gson = new Gson();
    }

    public static synchronized SharedPrefUtils getInstance(Context context) {
        if (instance == null) {
            instance = new SharedPrefUtils(context.getApplicationContext());
        }
        return instance;
    }

    // 保存基本数据类型的方法
    public void putString(String key, String value) {
        editor.putString(key, value).apply();
    }

    public String getString(String key, String defaultValue) {
        return sharedPreferences.getString(key, defaultValue);
    }

    public void putInt(String key, int value) {
        editor.putInt(key, value).apply();
    }

    public int getInt(String key, int defaultValue) {
        return sharedPreferences.getInt(key, defaultValue);
    }

    // 其他基本类型的put和get方法类似

    // 使用Gson来处理复杂对象的序列化和反序列化
    public void putObject(String key, Object obj) {
        String json = gson.toJson(obj);
        putString(key, json);
    }

    public <T> T getObject(String key, Class<T> a) {
        String json = getString(key, "");
        if (json.isEmpty()) {
            return null;
        } else {
            try {
                return gson.fromJson(json, a);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    // 删除指定key的数据
    public void remove(String key) {
        editor.remove(key).apply();
    }

    // 清除所有数据
    public void clear() {
        editor.clear().apply();
    }

    // 获取所有的键值对
    public Map<String, ?> getAll() {
        return sharedPreferences.getAll();
    }
}
